const BehaviorAll = require("../../../behaviors/behavior_all.js");
const ServiceProduct = require("../../../service/service_product.js");
const ServicePosition = require("../../../service/service_position.js");
const ServiceOrder = require("../../../service/service_order.js");
const ServiceProxyArea = require("../../../service/service_proxyArea.js");

module.exports = function (minPrice) {
  return {
    /**
     * behaviors
     */
    behaviors: [BehaviorAll],
    /**
     * 页面的初始数据
     */
    data: {
      /**
       * 产品数据格式：
          {
            id: 1, 
            name: "法国进口红酒拉斐天使庄园干红葡萄酒红酒整箱礼盒装750ml*6", 
            price: 100,
            imgUrl:''
          }
       */
      product: null,
      amount: 1,
      townId: null,
      fixAddress: null,
      minPrice: minPrice,
      minAmount: 1,
      /**
       * 代理区域数据格式
          [
            { 
              id: {
                productId: 1,
                townId: 2
              }, 
              addressData: {
                username: 'aa',
                phone: '123'
                fixAddress:"河北省/保定市/定兴县",
                address: 'xxxx'
              } 
            },
          ]
       */
      proxyData: [],
      /**
       * 级联相关
       */
      showedCascadePopup: false,
      /**
       * 收货地址相关
       */
      /**
       * 地址数据格式：
      {
        username: "张三",
        phone: 18011114522,
        address: "xxxxxxxxxxxx",
        fixAddress: "ssss"
      }
       */
      addressData: null,
      // 是否显示地址添加框
      addAddressShow: false
    },
    /**
     * 
     */
    methods: {
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function (options) {
        const _this = this;
        const productId = options.productId;
        const townId = options.townId;
        const fixAddress = options.fixAddress;
        if (null !== townId && undefined !== townId) {
          _this.setData({
            townId: townId,
            fixAddress: fixAddress
          });
        }
        // 产品
        ServiceProduct.findById(productId, function (data) {
          _this.setData({ product: data });
          // 处理最小数量
          const price = data.price;
          const minPrice = _this.data.minPrice;
          const minAmount = Math.ceil(minPrice / price);
          _this.setData({
            amount: minAmount,
            minAmount: minAmount
          });
        });
        // 代理
        ServiceProxyArea.listByProduct(productId, function (data) {
          _this.setData({ proxyData: data.records });
        });
      },

      onReady: function (e) {
        const _this = this;
        const townId = _this.data.townId;
        const fixAddress = _this.data.fixAddress;
        // 地址
        if (null !== townId && undefined !== townId) {
          ServiceProxyArea.getProxyAddress(townId, function (data) {
            _this.setData({
              addressData: data
            });
            if (fixAddress) {
              const addressData = _this.data.addressData;
              addressData.fixAddress = fixAddress;
              _this.setData({
                addressData,
                fixAddress: fixAddress,
                addAddressShow: true
              });
            }
          });
        }
      },

      /**
       * 编辑数量相关
       */
      product_onInputAmount: function (e) {
        const value = e.detail.value;
        this.setData({ amount: value })
      },
      product_onAddAmount: function (e) {
        const amount = Number(this.data.amount) + 1;
        this.setData({ amount: amount });
      },
      product_onSubAmount: function (e) {
        var amount = Number(this.data.amount) - 1;
        amount = amount < 1 ? 1 : amount;
        if (amount >= this.data.minAmount) {
          this.setData({ amount: amount });
        }
      },

      /**
      * 选择已有代理区域
      */
      onSelectedProxyArea: function (e) {
        const _this = this;
        const townId = e.detail.value;
        _this.setData({
          townId: townId
        });
        // 填充地址数据
        for (var value of _this.data.proxyData) {
          const id = value.id;
          if (id.productId === _this.data.product.id && id.townId === Number(townId)) {
            const addressData = value.addressData;
            _this.setData({
              addressData: addressData
            });
            break;
          }
        }
      },

      /**
      * 添加区域代理
      */
      onSelectedAddProxyArea: function () {
        const _this = this;
        _this.setData({ showedCascadePopup: true })
      },

      /**
       * 显示省份
       */
      onShowProvince: function (e) {
        const _this = this;
        ServicePosition.provinceList(data => {
          e.detail.callback(data.records);
        })
      },
      /**
       * 显示地级市
       */
      onShowCity: function (e) {
        const _this = this;
        ServicePosition.cityList(e.detail.level1.id, data => {
          e.detail.callback(data.records);
        })
      },
      /**
       * 显示县级市
       */
      onShowTown: function (e) {
        const _this = this;
        ServicePosition.townList(e.detail.level2.id, _this.data.product.id, data => {
          // 设置disabled功能
          for (var item of data.records) {
            item._disabled = item.selected;
          }
          // 回调
          e.detail.callback(data.records);
        })
      },
      /**
       * 选择县级市
       */
      onSelectTown: function (e) {
        const _this = this;
        //
        _this.setData({
          townId: e.detail.level3.id,
          showedCascadePopup: false,
          addAddressShow: true,
          fixAddress: e.detail.level1.name + '/' + e.detail.level2.name + '/' + e.detail.level3.name
        });
      },
      /**
       * 搜索
       */
      onSearch: function (e) {
        const _this = this;
        ServicePosition.search(e.detail.search.split(" "), function (data) {
          // 转换为所需格式
          const arr = [];
          for (var item of data.records) {
            arr.push({
              level1: { id: item.provinceId, name: item.provinceName },
              level2: { id: item.cityId, name: item.cityName },
              level3: { id: item.id, name: item.name }
            });
          }
          // 回调
          e.detail.callback(arr);
        });
      },

      /**
       * 点击编辑地址事件
       */
      onEditAddress: function () {
        const _this = this;
        _this.setData({
          addAddressShow: true,
          fixAddress: _this.data.addressData.fixAddress
        });
      },

      /**
       * 点击关闭地址事件
       */
      onCloseAddress: function () {
        const _this = this;
        _this.setData({
          addAddressShow: false
        });
      },

      /**
       * 提交新地址事件
       */
      onSubmitEditAddress: function (e) {
        const _this = this;
        _this.setData({
          addAddressShow: false,   // 关闭添加地址框
          addressData: {
            phone: e.detail.value.phone,
            username: e.detail.value.name,
            address: e.detail.value.address,
            fixAddress: e.detail.value.fixAddress
          }
        });
      },

      /**
      * 点击提交订单
      */
      onSubmitOrder: function (e) {
        const _this = this;
        // 验证
        if (null == _this.data.townId) {
          wx.showToast({
            title: '没有选择代理区域',
            icon: 'none'
          });
          return;
        }
        const minPrice = _this.data.minPrice;
        if (Number(_this.data.amount) * _this.data.product.price < minPrice) {
          wx.showToast({
            title: '订单金额不能少于' + minPrice + '元',
            icon: 'none'
          });
          return;
        }
        const addressData = _this.data.addressData;
        if (null == addressData || !addressData.username || !addressData.phone || !addressData.address) {
          wx.showToast({
            title: '地址信息不完整',
            icon: 'none'
          })
          return;
        }
        // 提交订单
        ServiceOrder.create(
          _this.data.product.id,
          _this.data.townId,
          addressData,
          _this.data.amount,
          function (data) {
            // 跳转到支付页面
            wx.navigateTo({ url: '../orderPayType/orderPayType?orderId=' + data.id });
          }
        );
      }
    }
  };

}